<template>
    <div>
        <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">添加</el-button>
        <!-- 表格 -->
        <!-- data 可以展示数据必须是数组
        label 表头 prop 展示数据的那个对象
        type 这一列的类型 一般为index 自动增长数字
        -->
        <el-table
            :data="trademarkList"
            border
            style="width: 100%;margin:20px 0">
            <el-table-column
                align="center"
                type="index"
                label="序号"
                width="80">
            </el-table-column>
            <el-table-column
                prop="tmName"
                label="品牌名称"
                width="180">
            </el-table-column>
            <el-table-column
                prop="logoUrl"
                label="品牌Logo"
                width="width">
                <!-- row代表的是data里面的每一项 -->
                <template slot-scope="{row,$index}">
                    <img :src="row.logoUrl" alt="" style="width:80px;height:60px">
                </template> 
            </el-table-column>
            <el-table-column
                prop="prop"
                label="操作"
                width="width">
                <template slot-scope="{row,$index}">
                    <el-button type="warning" icon="el-icon-edit" size="mini" @click="showUpdateDialog(row)">修改</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTrademark(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- element 分页器 
        4个数据 当前页 current-page 每页的数量page-size 总量total 连续数加上2个按钮的数量 pager-count 
        一个事件 @current-change="handleCurrentChange" 改变页面对应的事件
                @size-change="handleSizeChange" 改变每页数量的事件
        -->
        <el-pagination
            style="text-align:center"
            @current-change="getTrademarkList"
            @size-change="handleSizeChange"
            :current-page="page"
            :page-sizes="[3, 5, 10]"
            :page-size="limit"
            :pager-count="7"
            layout="prev, pager, next, jumper,->,sizes,total"
            :total="total">
        </el-pagination>
        <!-- 添加和修改的dialog -->
        <!-- 表单验证需要用到：model="tmForm" -->
        <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
            <el-form style="width:60%" :model="tmForm" :rules="rules" ref="tmForm">
                <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                    <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
                    <!-- action上传文件需要接口 -->
                    <el-upload
                    class="avatar-uploader"
                    action="/dev-api/admin/product/fileUpload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2M</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrupdateTrademark">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'Trademark',
    data() {
        return {
            page:1,
            limit:3,
            trademarkList:[],
            total:0,
            //控制dialog的显示或隐藏
            dialogFormVisible:false,
            // imageUrl: '',
            tmForm:{
                //指定需要收集的数据
                logoUrl:'',
                tmName:''
            },
            //表单验证规则
            rules:{
                tmName:{
                    required:true, message:'请输入品牌名称',trigger:'blur'
                },
                logoUrl:{
                    required:true, message:'请输入品牌logo',trigger:'blur'
                }
            }
        }
    },
    mounted() {
        this.getTrademarkList()
    },
    methods:{
        async getTrademarkList( page = 1) {
            this.page = page
            const result  = await this.$API.trademark.getPageList(this.page, this.limit)  
            if(result.code === 200 || result.code === 20000){
                this.trademarkList = result.data.records
                this.total = result.data.total
            }  
        },
        //修改每页显示的数量
        handleSizeChange(size){
            this.limit = size
            this.getTrademarkList()
        },
        //upload自带的
        //上传成功
        handleAvatarSuccess(res, file) {
            //获取本地的图片路径
            // this.imageUrl = URL.createObjectURL(file.raw);
            this.tmForm.logoUrl = res.data || file.response.data
        },
        //上传之前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 点击页面添加按钮使dialog显示
        showAddDialog(){
            //清空取消的from表单属性
            this.tmForm = {
                tmName:'',
                logoUrl:'',
            }
            this.dialogFormVisible=true
        },
        //点击修改显示修改的dialog
        showUpdateDialog(row){
            this.dialogFormVisible = true
            //不能直接赋值地址值会有bug
            this.tmForm = {...row}
        },
        //点击dialog的确定按钮添加或者修改 获取请求参数 整理其参数 发送请求 成功干啥失败干啥
        addOrupdateTrademark(){
            this.$refs.tmForm.validate(async (valid) => {
                if(valid) {
                    let trademark = this.tmForm
                    try {
                        const result = await this.$API.trademark.addOrUpdate(trademark)
                        if(result.code === 200 || result.code === 20000){
                            this.$message.success(trademark.id?'修改成功':'添加成功')
                            this.dialogFormVisible=false
                            //重新获取列表数据 但是添加与修改请求的页码不同
                            this.getTrademarkList(trademark.id?this.page:1)
                        }else{
                            this.$message.error(trademark.id?'修改失败':'添加失败')
                        }
                    } catch (error) {
                        this.$message.error('请求失败')
                    }
                }else {
                    this.$message.error('表单验证不合法')
                    return false
                }
            })

        },
        //点击删除按钮
        deleteTrademark(row) {
            this.$confirm(`你确定要删除${row.tmName}`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async () => {
                try {
                const result = await this.$API.trademark.delete(row.id)
                if(result.code === 200 || result.code === 20000){
                    this.$message.success('删除品牌成功'); 
                    this.getTrademarkList(this.trademarkList.length>1?this.page:this.page-1)
                }
                } catch (error) {
                    this.$message.error('删除品牌失败'); 
                }
            }).catch(() => {
                this.$message.info('已取消删除'); 
            });
        }
        
    }
}
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
